﻿using System;
using System.Collections.Generic;
using System.Linq;
using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;

namespace Pay.Service.Service {
    public class UserFeedBackService : ServiceBase, IUserFeedBackService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMerchantService _iMerchantService;

        public UserFeedBackService(IUnitOfWork iUnitOfWork, IMerchantService iMerchantService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iMerchantService = iMerchantService;
        }

        public int Add(user_feedback_dto dto) {
            UserFeedBack model = new UserFeedBack();
            dto.ToDtoObject<UserFeedBack>(model);
            context.userFeedBacks.Add(model);
            int result = _iUnitOfWork.Commit();
            dto.id = model.Id;
            return result;
        }

        /// <summary>
        /// 获得用户反馈列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<user_feedback_dto> GetUserFeedBacks(UserFeedBackQuery query) {
            var filter = PredicateBuilder.True<UserFeedBack>();
            if (!string.IsNullOrEmpty(query.name)) {
                filter = filter.And(c => c.Merchant.Name == query.name);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                long time = DateTime.Parse(query.begin_time).ToUnix();
                filter = filter.And(c => c.CreateTime >= time);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                long time = DateTime.Parse(query.end_time).AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime <= time);
            }
            var result = context.userFeedBacks.FromCachePaged<UserFeedBack, user_feedback_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(o => o.CreateTime));
            return result;
        }

        /// <summary>
        /// 获得用户反馈
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public user_feedback_dto GetUserFeedBack(long id) {
            return context.userFeedBacks.Find(id).ToDtoObject<user_feedback_dto>();
        }

        /// <summary>
        /// 回复反馈
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="manageId"></param>
        /// <returns></returns>
        public bool ReplyUserFeedBack(user_feedback_dto dto, long manageId) {
            if (string.IsNullOrEmpty(dto.reply_title))
                throw new ServerErrorException("回复标题不能为空");
            if (string.IsNullOrEmpty(dto.reply_content))
                throw new ServerErrorException("回复内容不能为空");
            var model = context.userFeedBacks.FindById(dto.id);
            if (!string.IsNullOrEmpty(model.ReplyTitle))
                throw new ServerErrorException("该反馈已进行过回复，请勿重复操作");
            var manager = context.Manages.FindById(manageId);
            var merchant = _iMerchantService.Get(model.UserId);
            model.ReplyTitle = dto.reply_title;
            model.ReplyContent = dto.reply_content;
            model.ReplyTime = DateTime.Now.ToUnix();
            model.ReplyUserMobile = manager.Mobile;
            //保存消息
            var replyMessage = new MessagePush();
            replyMessage.MerchantId = model.UserId;
            replyMessage.Type = MsgType.UserFeedBack;
            replyMessage.Title = model.ReplyTitle;
            replyMessage.ShortContent = model.ReplyTitle;
            replyMessage.Content = model.ReplyContent;
            replyMessage.Ext = "{}";
            replyMessage.CreateTime = DateTime.Now.ToUnix();
            replyMessage.ObjectId = model.Id;
            context.MessagePushs.Add(replyMessage);
            _iUnitOfWork.Commit();

            model.ReplyMsgId = replyMessage.Id;
            var result = _iUnitOfWork.Commit() > 0;

            //发送消息
            try {
                JPushHelp jPushHelp = new JPushHelp(t_RequestMethod.push_app_key, t_RequestMethod.push_app_secret);
                jPushHelp.Push(replyMessage.Title, replyMessage.Content, (int)replyMessage.Type, replyMessage.ObjectId.Value, new List<string> { merchant.mobile });
            }
            catch (Exception) { }

            return result;

        }
    }
}
